﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Dynamic;
using Microsoft.Practices.Unity;

namespace Skynet.LibraryModule.Presenter.ListPhotos
{
    public class ListPhotosPresenter : Infrastructure.Web.Views.Master.MasterPresenter<IListPhotosView>
    {
        [Dependency]
        public Infrastructure.CloudWeb.BusinessServices.IMethodAuditService MethodAuditService { get; set; }

        private CloudBlobContainer CreateBlobStorage(string containername)
        {
            var storageAccount = CloudStorageAccount.FromConfigurationSetting("InfrastructureConnectionString");
            CloudBlobClient blobStorage = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobStorage.GetContainerReference(containername);
            bool created = container.CreateIfNotExist();
            if (created)
            {
                var permissions = container.GetPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                container.SetPermissions(permissions);
            }

            return container;
        }

        public override void OnViewInitialized()
        {

            var audit = new Infrastructure.CloudWeb.Entities.MethodAudit();
            audit.Id = Guid.NewGuid();
            audit.Activity = Guid.NewGuid();
            audit.Application = "Skynetlibrary";
            audit.Created = DateTime.Now;
            audit.Method = "LoadImages";
            MethodAuditService.AddMethodAudit(audit);


            var store = this.CreateBlobStorage("photos");
            BlobRequestOptions opt = new BlobRequestOptions();
            opt.BlobListingDetails = BlobListingDetails.All;
            opt.UseFlatBlobListing = true;
            var items = store.ListBlobs(opt).ToList();
            var results = new HashSet<Tuple<string>>();
            foreach (var item in items)
            {
                var ex = new Tuple<string>(item.Uri.AbsoluteUri);

                results.Add(ex);
            }
            this.View.BlobItems = results;


            var audit2 = new Infrastructure.CloudWeb.Entities.MethodAudit();
            audit2.Id = Guid.NewGuid();
            audit2.Activity = Guid.NewGuid();
            audit2.Application = "Skynetlibrary";
            audit2.Created = DateTime.Now;
            audit2.Method = "LoadImages";
            MethodAuditService.AddMethodAudit(audit2);

        }
        public override void OnViewLoaded()
        {

        }
    }
}
